﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MuaChung.Base;
using MuaChung.doanhnghiepbiz;
using MuaChung.beatifulhousews;

namespace MuaChung.Models
{    
    /// <summary>
    /// Coupon info version 1.0
    /// </summary>    
    public partial class Coupon
    {

        private string _maCoupon;

        private string _maMatHang;

        private string _tenMatHang;

        private string _maNhaCungCap;

        private string _tenNhaCungCap;

        private string _giaHangKhiChuaGiam;

        private string _giaHangSauKhiGiam;

        private string _donViTien;

        private int _soLuongThoaCoupon;

        private int _soLuongMuaLonNhat;

        private int _soLuongDaDat;

        private System.DateTime _ngayBatDau;

        private System.DateTime _ngayKetThuc;

        private System.DateTime _ngayCouponBatDauDuocSuDung;

        private System.DateTime _ngayCouponHetHan;

        private string _thongTinMoTa;

        private string _dieuKienSuDung;

        private string[] _linkHinhAnh;
        //-------------------------------------
        //---------------------------------------------------
        /// <remarks/>
        public string MaCoupon
        {
            get
            {
                return this._maCoupon;
            }
            set
            {
                this._maCoupon = value;
            }
        }

        /// <remarks/>
        public string MaMatHang
        {
            get
            {
                return this._maMatHang;
            }
            set
            {
                this._maMatHang = value;
            }
        }

        /// <remarks/>
        public string TenMatHang
        {
            get
            {
                return this._tenMatHang;
            }
            set
            {
                this._tenMatHang = value;
            }
        }

        /// <remarks/>
        public string MaNhaCungCap
        {
            get
            {
                return this._maNhaCungCap;
            }
            set
            {
                this._maNhaCungCap = value;
            }
        }

        /// <remarks/>
        public string TenNhaCungCap
        {
            get
            {
                return this._tenNhaCungCap;
            }
            set
            {
                this._tenNhaCungCap = value;
            }
        }

        /// <remarks/>
        public string GiaHangKhiChuaGiam
        {
            get
            {
                return this._giaHangKhiChuaGiam;
            }
            set
            {
                this._giaHangKhiChuaGiam = value;
            }
        }

        /// <remarks/>
        public string GiaHangSauKhiGiam
        {
            get
            {
                return this._giaHangSauKhiGiam;
            }
            set
            {
                this._giaHangSauKhiGiam = value;
            }
        }

        /// <remarks/>
        public string DonViTien
        {
            get
            {
                return this._donViTien;
            }
            set
            {
                this._donViTien = value;
            }
        }

        /// <remarks/>
        public int SoLuongThoaCoupon
        {
            get
            {
                return this._soLuongThoaCoupon;
            }
            set
            {
                this._soLuongThoaCoupon = value;
            }
        }

        /// <remarks/>
        public int SoLuongMuaLonNhat
        {
            get
            {
                return this._soLuongMuaLonNhat;
            }
            set
            {
                this._soLuongMuaLonNhat = value;
            }
        }

        /// <remarks/>
        public int SoLuongDaDat
        {
            get
            {
                return this._soLuongDaDat;
            }
            set
            {
                this._soLuongDaDat = value;
            }
        }

        /// <remarks/>
        public System.DateTime NgayBatDau
        {
            get
            {
                return this._ngayBatDau;
            }
            set
            {
                this._ngayBatDau = value;
            }
        }

        /// <remarks/>
        public System.DateTime NgayKetThuc
        {
            get
            {
                return this._ngayKetThuc;
            }
            set
            {
                this._ngayKetThuc = value;
            }
        }

        /// <remarks/>
        public System.DateTime NgayCouponBatDauDuocSuDung
        {
            get
            {
                return this._ngayCouponBatDauDuocSuDung;
            }
            set
            {
                this._ngayCouponBatDauDuocSuDung = value;
            }
        }

        /// <remarks/>
        public System.DateTime NgayCouponHetHan
        {
            get
            {
                return this._ngayCouponHetHan;
            }
            set
            {
                this._ngayCouponHetHan = value;
            }
        }

        /// <remarks/>
        public string ThongTinMoTa
        {
            get
            {
                return this._thongTinMoTa;
            }
            set
            {
                this._thongTinMoTa = value;
            }
        }

        /// <remarks/>
        public string DieuKienSuDung
        {
            get
            {
                return this._dieuKienSuDung;
            }
            set
            {
                this._dieuKienSuDung = value;
            }
        }

        /// <remarks/>
        public string[] LinkHinhAnh
        {
            get
            {
                return this._linkHinhAnh;
            }
            set
            {
                this._linkHinhAnh = value;
            }
        }
    }
    public class CouponView
    {
        public int status { get; set; }
        public Coupon cp { get; set; }
    }
    public class CouponDetail
    {
        public int cid { get; set; }
        public string maCoupon { get; set; }
        public string tenSP { get; set; }
        public int maLoai { get; set; }
        public string tenLoai { get; set; }
        public int soLuongCanMua { get; set; }
        public int soLuongDatHang { get; set; }
        public int soLuongCoupon { get; set; }
        public DateTime tgBatDau { get; set; }
        public DateTime tgKetThuc { get; set; }
        public DateTime tgDuocSuDung { get; set; }
        public DateTime tgHetHan { get; set; }
        public double tyLeGiam { get; set; }
        public decimal giaTot { get; set; }
        public decimal giaGoc { get; set; }
        public decimal giaThuong { get; set; }
        public decimal giaB2B { get; set; }
        public string moTa { get; set; }
        public string dieuKien { get; set; }
        public string moTaTomTat { get; set; }
        public List<IMAGE_COUPON> hinhAnh { get; set; }
        public DOANHNGHIEP doanhNghiep { get; set; }
    }
    public class CouponDetailMin
    {
        public int cid { get; set; }
        public string hinhAnh { get; set; }
        public string maCoupon { get; set; }
        public string tenSP { get; set; }        
        public string tenDoanhNghiep { get; set; }
        public int maLoai { get; set; }
        public string tenLoai { get; set; }
        public DateTime tgBatDau { get; set; }
        public DateTime tgKetThuc { get; set; }
        public double tyLeGiam { get; set; }
        public decimal giaTot { get; set; }
        public decimal giaGoc { get; set; }
        public int soLuongDatHang { get; set; }
        public int soLuongCanMua { get; set; }
        public int soLuongMax { get; set; }
        public string trangThai { get; set; }
        public string serverLinkCoupon { get; set; }
    }
    public class PagingModel
    {
        public int currentPage;
        public int totalPage;
        public string url;
    }
    public class OrderCouponModel
    {
        public int Ma_TK { get; set; }
        public string HoTen { get; set; }
        public DateTime NgaySinh { get; set; }
        public string DiaChi { get; set; }
        public string SoDienThoai { get; set; }        
        public List<DONHANG> lstOrder { get; set; }
        public int status { get; set; }
    }
    public class CouponModel
    {
        private static MuaChungEntities db = new MuaChungEntities();
        public static OrderCouponModel Cart = new OrderCouponModel();
        public static bool InitCart(string userName)
        {
            TAI_KHOAN tk = AccountModel.FindByUsername(userName);
            CHITIET_TAIKHOAN cttk = AccountModel.FindDetail(tk.Username);
            Cart.Ma_TK = tk.ID;
            Cart.HoTen = cttk.HoTen;
            Cart.NgaySinh = cttk.NgaySinh;
            Cart.SoDienThoai = cttk.DienThoai;
            Cart.DiaChi = cttk.DiaChi;
            Cart.lstOrder = new List<DONHANG>();
            return true;
        }
        public static List<COUPON> GetAll(int currentPage = 1, int pageSize = 10, int orderBy = 1)
        {
            List<COUPON> lst = new List<COUPON>();
            int startindex = pageSize * (currentPage - 1);
            int endindex = pageSize * currentPage;
            try
            {
                if (orderBy == 1)
                {
                    var query = (from n in db.COUPONs
                                 orderby n.ThoiGian_BatDau descending
                                 select n).Skip(startindex);
                    if (query.Count() > 0)
                    {
                        return query.Take(pageSize).ToList();
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    var query = (from n in db.COUPONs
                                 orderby n.SoLuong_DaDat descending
                                 select n).Skip(startindex);
                    if (query.Count() > 0)
                    {
                        return query.Take(pageSize).ToList();
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            catch { return null; }            
        }        
        public static COUPON FindByID(int id)
        {
            try
            {
                var query = from n in db.COUPONs
                            where n.ID == id
                            select n;
                return query.First();
            }
            catch
            {
                return null;
            }
        }
        public static COUPON FindByMaCoupon(string maCoupon)
        {
            try
            {
                var query = from n in db.COUPONs
                            where n.Ma_Coupon == maCoupon
                            select n;
                return query.First();
            }
            catch
            {
                return null;
            }
        }
        public static CHITIET_COUPON GetCouponDetail(int id)
        {
            try {
                var query = from n in db.CHITIET_COUPON
                            where n.Ma_Coupon == id
                            select n;
                return query.First();
            }
            catch { return null; }
        }
        public static int GetNumberOfCoupon()
        {
            try
            {
                var query = from n in db.COUPONs
                            select n;
                return query.Count();
            }
            catch
            {
                return -1;
            }
        }
        public static List<COUPON> GetNewCoupon(int numberCoupon)
        {
            try
            {
                var query = (from n in db.COUPONs
                            orderby n.ThoiGian_BatDau ascending
                            select n).Take(numberCoupon);
                return query.ToList();
            }
            catch { return null; }
        }
        public static List<COUPON> GetHotCoupon(int numberCoupon)
        {
            try
            {
                var query = (from n in db.COUPONs
                             orderby n.SoLuong_DaDat descending
                             select n).Take(numberCoupon);
                return query.ToList();
            }
            catch { return null; }
        }
        public static List<COUPON> SearchCoupon(string keyWord, int currentPage = 1, int pageSize = 10)
        {
            try
            {
                var query = from n in db.COUPONs
                            where n.Ten_SanPham.Contains(keyWord) || n.DOANHNGHIEP.Ten_DoanhNghiep.Contains(keyWord)
                            select n;
                return query.ToList();
            }
            catch
            { return null; }
        }
        public static bool AddRegisteredCoupon(Coupon cp,int wsID)
        {
            COUPON c = new COUPON();
            CHITIET_COUPON ctcp = new CHITIET_COUPON();
            WEBSERVICE sv = ServiceModel.FindWSByID(wsID);
            c.Ma_Coupon = cp.MaCoupon;
            c.Ten_SanPham = cp.TenMatHang;
            c.ThoiGian_BatDau = cp.NgayBatDau;
            c.ThoiGian_KetThuc = cp.NgayKetThuc;
            c.ThoiGian_DuocSuDung = cp.NgayCouponBatDauDuocSuDung;
            c.ThoiGian_HetHan = cp.NgayCouponHetHan;
            c.SoLuong_CanMua = cp.SoLuongThoaCoupon;
            c.SoLuong_Max = cp.SoLuongMuaLonNhat;
            c.SoLuong_DaDat = cp.SoLuongDaDat;
            c.Gia_Tot = Convert.ToDecimal(cp.GiaHangSauKhiGiam);
            c.Gia_Goc = Convert.ToDecimal(cp.GiaHangKhiChuaGiam);
            c.TyLeGiam = (int)(((c.Gia_Goc-c.Gia_Tot) * 100) / c.Gia_Goc);
            c.Ma_Webservice = wsID;
            c.Ma_DoanhNghiep = sv.Ma_DoanhNghiep;
            ctcp.DieuKienSuDung = cp.DieuKienSuDung;
            ctcp.Ma_NhaCungCap = cp.MaNhaCungCap;
            ctcp.Ten_NhaCungCap = cp.TenNhaCungCap;
            ctcp.MoTa = cp.ThongTinMoTa;
            try
            {
                db.AddToCOUPONs(c);
                db.SaveChanges();
                //COUPON tmp = FindByMaCoupon(c.Ma_Coupon);
                ctcp.Ma_Coupon = c.ID;
                int i = 1;
                foreach (var item in cp.LinkHinhAnh)
                {
                    IMAGE_COUPON imgtmp = new IMAGE_COUPON();
                    imgtmp.Ma_Coupon = c.ID;
                    imgtmp.URL = item;
                    imgtmp.Sott = i;
                    i++;
                    db.AddToIMAGE_COUPON(imgtmp);
                }
                db.AddToCHITIET_COUPON(ctcp);
                db.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }            
        }
        public static bool OrderCouponsInCart()
        {
            WebServiceDoanhNghiepBiz ws5a = new WebServiceDoanhNghiepBiz();
            Service1 ws2b = new Service1();            
            string sid = string.Empty;
            foreach (var item in Cart.lstOrder)
            {
                int wsid = Convert.ToInt32(item.COUPON.Ma_Webservice);
                WEBSERVICE sv = ServiceModel.FindWSByID(wsid);
                string code = string.Empty;
                bool validate = true;
                //if (sv.Ma_WS == BaseWeb.WS_BIZ5A)
                //{
                //    try
                //    {                        
                //        sid = ws5a.Authenticate(sv.WSUSERNAME, sv.WSPASSWORD);
                //        code = ws5a.OrderCoupon(sid, item.COUPON.Ma_Coupon, item.SoLuong);
                //        validate = ws5a.ValidateOrder(sid, code);                                
                //    }
                //    catch
                //    {
                //        Cart.status = 0;
                //        return false;
                //    }
                //}
                //else if (sv.Ma_WS == BaseWeb.WS_BIZ2B)
                //{
                //    try
                //    {                        
                //        sid = ws2b.Authenticate(sv.WSUSERNAME, sv.WSPASSWORD);
                //        code = ws2b.OrderCoupon(sid, item.COUPON.Ma_Coupon, item.SoLuong);
                //        validate = ws2b.ValidateOrder(sid, code);
                //    }
                //    catch
                //    {
                //        Cart.status = 0;
                //        return false;
                //    }
                //}
                if (validate)
                {
                    DONHANG tmp = new DONHANG();
                    tmp.Ma_Coupon = item.Ma_Coupon;
                    tmp.NgayDatHang = DateTime.Now;
                    tmp.Gia = item.Gia;
                    tmp.SoLuong = item.SoLuong;
                    tmp.TongGia = item.TongGia;
                    tmp.Ma_TK = CouponModel.Cart.Ma_TK;
                    tmp.TrangThai = 1;
                    item.TrangThai = 1;
                    item.Ma_DonHang = code;
                    tmp.Ma_DonHang = code;
                    DonHangModels.Add(tmp);
                    COUPON cp = FindByID(item.Ma_Coupon);
                    cp.SoLuong_DaDat += item.SoLuong;
                    cp.SoLuong_CanMua -= item.SoLuong;
                    UpdateCoupon(cp);
                }                
            }
            bool OK = false;
            int i = 0;
            while (!OK)
            {
                if (Cart.lstOrder[i].TrangThai == 1)
                {
                    Cart.lstOrder.Remove(Cart.lstOrder[i]);
                }
                else { i++; }
                if (i >= Cart.lstOrder.Count)
                {
                    OK = true;
                }
            }
            Cart.status = 1;
            return true;
        }
        public static bool UpdateCoupon(COUPON cp)
        {
            try
            {
                db.COUPONs.ApplyCurrentValues(cp);
                db.SaveChanges();
            }
            catch { return false; }
            return true;
        }
        public static bool DeleteCoupon(COUPON cp)
        {
            try
            {
                db.COUPONs.DeleteObject(cp);
                db.SaveChanges();
            }
            catch { return false; }
            return true;
        }
        public static bool UpdateCouponInfo(CHITIET_COUPON ctcp)
        {
            try
            {
                db.CHITIET_COUPON.ApplyCurrentValues(ctcp);
                db.SaveChanges();
            }
            catch { return false; }
            return true;
        }
        public static CouponDetailMin ToCouponDetailMin(COUPON item)
        {
            CouponDetailMin tmp = new CouponDetailMin();
            tmp.cid = item.ID;
            tmp.giaGoc = item.Gia_Goc;
            tmp.giaTot = item.Gia_Tot;
            tmp.maCoupon = item.Ma_Coupon;
            tmp.maLoai = Convert.ToInt32(item.Ma_Loai);
            //tmp.tenLoai = item.LOAI_COUPON.TenLoai;
            tmp.tgBatDau = item.ThoiGian_BatDau;
            tmp.tgKetThuc = item.ThoiGian_KetThuc;
            tmp.tyLeGiam = Convert.ToDouble(item.TyLeGiam);
            tmp.tenSP = item.Ten_SanPham;
            tmp.soLuongDatHang = item.SoLuong_DaDat;
            tmp.soLuongCanMua = item.SoLuong_CanMua;
            tmp.soLuongMax = item.SoLuong_Max;
            tmp.tenDoanhNghiep = item.DOANHNGHIEP.Ten_DoanhNghiep;
            try
            {
                tmp.hinhAnh = item.IMAGE_COUPON.First().URL;
            }
            catch
            {
                tmp.hinhAnh = null;
            }
            if (item.SoLuong_DaDat >= item.SoLuong_Max)
            {
                tmp.trangThai = "ChayHang";
            }
            else
            {
                tmp.trangThai = "ConHang";
            }
            return tmp;
        }        
        public static bool UpdateCouponFromWebservice(int cid)
        {
            COUPON c = FindByID(cid);
            WEBSERVICE sv = c.WEBSERVICE;
            Coupon cp = new Coupon();
            if (sv.Ma_WS == BaseWeb.WS_BIZ5A)
            {
                WebServiceDoanhNghiepBiz ws5a = new WebServiceDoanhNghiepBiz();
                string sid = ws5a.Authenticate(sv.WSUSERNAME, sv.WSPASSWORD);
                cp = ws5a.FindCouponInfo(sid, c.Ma_Coupon);
            }
            else if(sv.Ma_WS == BaseWeb.WS_BIZ2B)
            {
                Service1 ws2b = new Service1();
                string sid = ws2b.Authenticate(sv.WSUSERNAME, sv.WSPASSWORD);
                cp = ws2b.FindCouponInfo(sid, c.Ma_Coupon);
            }            
            CHITIET_COUPON ctcp = GetCouponDetail(cid);
            c.Ma_Coupon = cp.MaCoupon;
            c.Ten_SanPham = cp.TenMatHang;
            c.ThoiGian_BatDau = cp.NgayBatDau;
            c.ThoiGian_KetThuc = cp.NgayKetThuc;
            c.ThoiGian_DuocSuDung = cp.NgayCouponBatDauDuocSuDung;
            c.ThoiGian_HetHan = cp.NgayCouponHetHan;
            c.SoLuong_CanMua = cp.SoLuongThoaCoupon;
            c.SoLuong_Max = cp.SoLuongMuaLonNhat;
            c.SoLuong_DaDat = cp.SoLuongDaDat;
            c.Gia_Tot = Convert.ToDecimal(cp.GiaHangSauKhiGiam);
            c.Gia_Goc = Convert.ToDecimal(cp.GiaHangKhiChuaGiam);
            c.TyLeGiam = (int)(((c.Gia_Goc - c.Gia_Tot) * 100) / c.Gia_Goc);
            c.Ma_Webservice = sv.ID;
            ctcp.DieuKienSuDung = cp.DieuKienSuDung;
            ctcp.Ma_NhaCungCap = cp.MaNhaCungCap;
            ctcp.Ten_NhaCungCap = cp.TenNhaCungCap;
            ctcp.MoTa = cp.ThongTinMoTa;
            try
            {
                UpdateCoupon(c);
                UpdateCouponInfo(ctcp);
                return true;                          
            }
            catch
            {
                return false;
            }           
        }
        public static bool AddCoupon(COUPON cp, CHITIET_COUPON ctcp)
        {

            try
            {
                db.AddToCOUPONs(cp);
                db.SaveChanges();
                ctcp.Ma_Coupon = FindByMaCoupon(cp.Ma_Coupon).ID;

                db.AddToCHITIET_COUPON(ctcp);
                db.SaveChanges();
                return true;

            }
            catch
            {
                return false;
            }
        }
    }
}